package com.hp.appfw.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.model.PushUnicastMessageRequest;
import com.baidu.yun.channel.model.PushUnicastMessageResponse;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;

public class PushUtil {
	protected final Log logger = LogFactory.getLog(PushUtil.class);

	public static final int DEVICE_WEB = 1;
	public static final int DEVICE_PC = 2;
	public static final int DEVICE_ANDROID = 3;
	public static final int DEVICE_IOS = 4;
	public static final int DEVICE_WP = 5;
	
	private String apiKey;
	private String secretKey;
	
	public boolean push(String msgId, int type, long channelId, String userId, String message)
	{
        ChannelKeyPair pair = new ChannelKeyPair(apiKey, secretKey);

        BaiduChannelClient channelClient = new BaiduChannelClient(pair);

        channelClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                logger.info(event.getMessage());
            }
        });

        try {

            PushUnicastMessageRequest request = new PushUnicastMessageRequest();
            request.setMessageType(1);
            request.setDeviceType(type); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            if(type == PushUtil.DEVICE_IOS)
            {
            	request.setDeployStatus(2);// DeployStatus => 1: Developer 2: Production
            }
            request.setChannelId(channelId);
            request.setUserId(userId);
            request.setMessage(message);
            request.setMsgKey(msgId);

            PushUnicastMessageResponse response = channelClient.pushUnicastMessage(request);
            

            logger.info("Push amount:" + response.getSuccessAmount() + "\r\ntype:" + type + "\r\nchannelId:" + channelId + "\r\nuserId:" + userId + "\r\nmessage:" + message);

            return true;
        } 
        catch (Exception e) 
        {
            logger.error("Push error:" + e.toString() + "\r\ntype:" + type + "\r\nchannelId:" + channelId + "\r\nuserId:" + userId + "\r\nmessage:" + message);
            
            return false;
        }
	}

	public String getSecretKey() {
		return secretKey;
	}
	public void setSecretKey(String secretKey) {
		this.secretKey = secretKey;
	}
	public String getApiKey() {
		return apiKey;
	}
	public void setApiKey(String apiKey) {
		this.apiKey = apiKey;
	}

}
